package org.xqh.study.google.guava;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName GuavaTest2
 * @Description TODO
 * @Author xuqianghui
 * @Date 2021/5/25 11:43
 * @Version 1.0
 */
public class GuavaTest2 {

    public static final String test = "%s|%s";

    public static final String key = "key";

    /**
     * guava cache test
     */
    public LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000)
            .refreshAfterWrite(3, TimeUnit.SECONDS)// 3秒刷新数据, 一个线程去获取最新值, 其他可以先获取旧的缓存值 返回.
            .expireAfterWrite(3, TimeUnit.SECONDS) // 3秒刷新数据, 一个线程获取最新值 其他所有线程阻塞等待
            .expireAfterAccess(3, TimeUnit.SECONDS) // 限定时间内 没有 访问 该数据, 会 执行异步 刷新缓存数据方法.
            .build(
                    new CacheLoader<String, String>() {
                        @Override
                        public String load(String s) throws Exception {
                            return loadValue(s);
                        }
                    }
            );

    public String loadValue(String key){
        String id = UUID.randomUUID().toString();
        String value = String.format(test, id, key);
        System.out.println("start to load new value: "+value);
        return value;
    }

    public static void main(String[] args) throws InterruptedException {
        GuavaTest2 test2 = new GuavaTest2();
        System.out.println(test2.getCache());
        Thread.sleep(12000);
        System.out.println(test2.getCache());

    }

    public String getCache(){
        return cache.getUnchecked(key);
    }


}
